'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { action, ...params } = event;
  
  try {
    switch (action) {
      case 'getUserList':
        return await getUserList(params);
      case 'getMessages':
        return await getMessages(params);
      case 'sendMessage':
        return await sendMessage(params);
      case 'markRead':
        return await markRead(params);
      case 'getUserProfile':
        return await getUserProfile(params);
      case 'getUserStatistics':
        return await getUserStatistics(params);
      case 'adjustUserPoints':
        return await adjustUserPoints(params);
      case 'toggleUserStatus':
        return await toggleUserStatus(params);
      case 'searchMessages':
        return await searchMessages(params);
      case 'getMessageStatistics':
        return await getMessageStatistics(params);
      case 'exportMessages':
        return await exportMessages(params);
      case 'adjustPoints':
        return await adjustPoints(params);
      case 'adjustCreditScore':
        return await adjustCreditScore(params);
      case 'updateCreditLevel':
        return await updateCreditLevel(params);
      case 'handleViolation':
        return await handleViolation(params);
      default:
        return { code: 400, msg: '未知操作' };
    }
  } catch (error) {
    console.error('adminChat云函数错误:', error);
    return { code: 500, msg: '服务器错误', error: error.message };
  }
};

// 获取有聊天记录的用户列表
async function getUserList({ page = 1, pageSize = 20, keyword = '' }) {
  try {
    // 从客服消息表查询消息
    let whereCondition = {
      // 排除系统消息
      senderId: db.command.neq('system'),
      receiverId: db.command.neq('system')
    };
    
    if (keyword) {
      whereCondition = db.command.and([
        whereCondition,
        db.command.or([
          { senderNickname: new RegExp(keyword, 'i') },
          { receiverNickname: new RegExp(keyword, 'i') }
        ])
      ]);
    }
    
    const messagesResult = await db.collection('customer-service-messages')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .limit(1000)
      .get();
    
    console.log(`[adminChat] 从customer-service-messages表查询到消息总数: ${messagesResult.data.length}`);
    
    if (!messagesResult.data || messagesResult.data.length === 0) {
      return {
        code: 200,
        msg: '获取成功',
        data: []
      };
    }
    
    // 手动处理用户分组
    const userMap = new Map();
    
    messagesResult.data.forEach(msg => {
      let userId, userNickname, userAvatar;
      
      // 确定用户信息（排除customer_service）
      if (msg.senderId === 'customer_service') {
        userId = msg.receiverId;
        userNickname = msg.receiverNickname;
        userAvatar = msg.receiverAvatar;
      } else if (msg.receiverId === 'customer_service') {
        userId = msg.senderId;
        userNickname = msg.senderNickname;
        userAvatar = msg.senderAvatar;
      } else {
        // 跳过非客服相关消息
        return;
      }
      
      if (userId && userId !== 'customer_service' && userId !== 'admin') {
        if (!userMap.has(userId) || new Date(msg.createTime) > new Date(userMap.get(userId).lastMessageTime)) {
          // 处理最后消息的显示内容
          let lastMessage = msg.content || '';
          if (msg.messageType === 'image') {
            lastMessage = '[图片]';
          } else if (msg.messageType === 'file') {
            lastMessage = '[文件]';
          } else if (msg.messageType === 'voice') {
            lastMessage = '[语音]';
          }
          
          userMap.set(userId, {
            id: userId,
            nickname: userNickname || '未知用户',
            avatar: userAvatar || '',
            lastMessage: lastMessage,
            lastMessageTime: msg.createTime,
            lastMessageType: msg.messageType,
            unreadCount: 0,
            isOnline: false,
            tags: []
          });
        }
      }
    });
    
    // 计算未读消息数量
    for (let [userId, userInfo] of userMap) {
      const unreadCount = messagesResult.data.filter(msg => 
        msg.senderId === userId && 
        msg.receiverId === 'customer_service' && 
        msg.status !== 'read'
      ).length;
      
      userInfo.unreadCount = unreadCount;
      userInfo.tags = unreadCount > 5 ? ['重要'] : unreadCount > 0 ? ['新消息'] : [];
    }
    
    console.log(`[adminChat] 用户列表数量: ${userMap.size}`);
    
    // 转换为数组并排序
    const users = Array.from(userMap.values())
      .sort((a, b) => new Date(b.lastMessageTime) - new Date(a.lastMessageTime))
      .slice((page - 1) * pageSize, page * pageSize);
    
    return {
      code: 200,
      msg: '获取成功',
      data: users
    };
  } catch (error) {
    console.error('[adminChat] 获取用户列表失败:', error);
    return {
      code: 500,
      msg: '获取用户列表失败: ' + error.message,
      data: []
    };
  }
}

// 获取与指定用户的聊天消息
async function getMessages({ userId, page = 1, pageSize = 50, beforeTime = null }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 构建基础查询条件
    let whereCondition = db.command.or([
      db.command.and([
        { senderId: userId },
        { receiverId: 'customer_service' }
      ]),
      db.command.and([
        { senderId: 'customer_service' },
        { receiverId: userId }
      ])
    ]);
    
    // 如果指定了时间点，只查询该时间点之前的消息（用于向上加载更早的历史消息）
    if (beforeTime) {
      whereCondition = db.command.and([
        whereCondition,
        { createTime: db.command.lt(new Date(beforeTime)) }
      ]);
    }
    
    const result = await db.collection('customer-service-messages')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    // 标记用户消息为已读
    try {
      await db.collection('customer-service-messages')
        .where({
          senderId: userId,
          receiverId: 'customer_service',
          status: db.command.neq('read')
        })
        .update({
          status: 'read',
          readTime: new Date()
        });
    } catch (updateError) {
      console.log('标记已读失败:', updateError);
    }

    // 获取用户的真实昵称和头像（如果消息中没有保存）
    let userInfo = null;
    try {
      const userResult = await db.collection('uni-id-users')
        .where({ _id: userId })
        .field({ nickname: true, avatar_file: true })
        .get();
      
      if (userResult.data && userResult.data.length > 0) {
        const user = userResult.data[0];
        userInfo = {
          nickname: user.nickname || '用户',
          avatar: user.avatar_file?.url || ''
        };
        console.log('获取到用户信息:', userInfo);
      }
    } catch (userError) {
      console.log('获取用户信息失败:', userError);
    }

    // 处理图片消息的URL
    const processedMessages = await Promise.all(result.data.reverse().map(async (msg) => {
      let content = msg.content;
      let imageUrl = msg.imageUrl; // 获取专门的图片URL字段
      
      // 如果是图片消息，需要处理图片URL
      if (msg.messageType === 'image') {
        const urlToProcess = imageUrl || content;
        
        console.log('处理图片消息:', {
          messageId: msg._id,
          originalContent: msg.content,
          originalImageUrl: msg.imageUrl,
          urlToProcess: urlToProcess
        });
        
        // 检查URL类型并处理
        if (urlToProcess && urlToProcess.startsWith('cloud://')) {
          // 处理云存储URL，获取临时访问链接
          try {
            const getTempUrlRes = await uniCloud.getTempFileURL({
              fileList: [urlToProcess]
            });
            
            if (getTempUrlRes.fileList && getTempUrlRes.fileList.length > 0) {
              content = getTempUrlRes.fileList[0].tempFileURL || urlToProcess;
              console.log('云存储URL转换成功:', urlToProcess, '->', content);
            }
          } catch (error) {
            console.log('获取图片临时链接失败:', error, '原URL:', urlToProcess);
            content = urlToProcess; // 保持原URL
          }
        } else if (urlToProcess && urlToProcess.startsWith('http://tmp/')) {
          // 临时路径，这种URL是无效的，需要清理
          console.warn('发现无效的临时路径:', urlToProcess);
          content = ''; // 清空无效URL
        } else if (urlToProcess && (urlToProcess.startsWith('http://') || urlToProcess.startsWith('https://'))) {
          // HTTP/HTTPS URL，直接使用
          content = urlToProcess;
          console.log('使用HTTP URL:', urlToProcess);
        } else {
          // 其他情况，可能是无效URL
          console.warn('无法识别的图片URL格式:', urlToProcess);
          content = urlToProcess || '';
        }
        
        // 记录最终处理结果
        console.log('图片消息处理完成:', {
          messageId: msg._id,
          finalContent: content,
          isValidUrl: content && (content.startsWith('http://') || content.startsWith('https://'))
        });
        
        // 如果处理后仍然没有有效的URL，设置为图片占位符
        if (!content || (!content.startsWith('http://') && !content.startsWith('https://'))) {
          console.error('图片消息缺少有效URL:', {
            messageId: msg._id,
            content: msg.content,
            imageUrl: msg.imageUrl,
            finalContent: content
          });
          content = '[图片]'; // 设置为文本占位符
        }
      }
      
      // 确定发送者信息
      let senderName, senderAvatar;
      if (msg.senderId === 'customer_service') {
        senderName = '客服小助手';
        senderAvatar = '';
      } else {
        // 优先使用消息中保存的信息，如果没有则使用查询到的用户信息
        senderName = msg.senderNickname || (userInfo?.nickname) || '用户';
        senderAvatar = msg.senderAvatar || (userInfo?.avatar) || '';
      }
      
      return {
        id: msg._id,
        type: msg.messageType,
        content: content,
        imageUrl: msg.imageUrl, // 保留原始的 imageUrl 字段
        senderName: senderName,
        isAdmin: msg.senderId === 'customer_service',
        createTime: msg.createTime,
        status: msg.status,
        avatar: senderAvatar
      };
    }));

    return {
      code: 200,
      msg: '获取成功',
      data: processedMessages
    };
  } catch (error) {
    console.error('获取消息失败:', error);
    return {
      code: 500,
      msg: '获取消息失败: ' + error.message,
      data: []
    };
  }
}

// 发送消息
async function sendMessage({ userId, content, type = 'text', imageUrl }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    const messageData = {
      messageType: type,
      senderId: 'customer_service',
      senderNickname: '客服小助手',
      senderAvatar: '',
      receiverId: userId,
      receiverNickname: '用户',
      receiverAvatar: '',
      content: content,
      createTime: new Date(),
      status: 'sent'
    };

    // 如果是图片消息，保存imageUrl字段
    if (type === 'image') {
      messageData.imageUrl = imageUrl || content;
      // 对于图片消息，content字段保存为简短描述
      messageData.content = '[图片]';
    }

    // 尝试获取接收者信息
    try {
      const userResult = await db.collection('uni-id-users')
        .where({ _id: userId })
        .field({ nickname: true, avatar_file: true })
        .get();
      
      if (userResult.data && userResult.data.length > 0) {
        const user = userResult.data[0];
        messageData.receiverNickname = user.nickname || '用户';
        messageData.receiverAvatar = user.avatar_file?.url || '';
      }
    } catch (userError) {
      console.log('获取用户信息失败:', userError);
    }

    const result = await db.collection('customer-service-messages').add(messageData);

    return {
      code: 200,
      msg: '发送成功',
      data: {
        id: result.id,
        type: messageData.messageType,
        content: messageData.content,
        imageUrl: messageData.imageUrl || '',
        senderName: '客服小助手',
        isAdmin: true,
        createTime: messageData.createTime,
        status: messageData.status,
        avatar: messageData.senderAvatar
      }
    };
  } catch (error) {
    console.error('发送消息失败:', error);
    return {
      code: 500,
      msg: '发送消息失败: ' + error.message,
      data: null
    };
  }
}

// 标记消息已读
async function markRead({ userId }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    const result = await db.collection('chatMessages')
      .where({
        senderId: userId,
        receiverId: 'admin',
        status: db.command.neq('read')
      })
      .update({
        status: 'read',
        readTime: new Date()
      });

    return {
      code: 200,
      msg: '标记成功',
      data: { updatedCount: result.updated }
    };
  } catch (error) {
    console.error('标记已读失败:', error);
    return {
      code: 500,
      msg: '标记已读失败: ' + error.message,
      data: { updatedCount: 0 }
    };
  }
}

// 获取用户详细资料
async function getUserProfile({ userId }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 查询用户基本信息
    const userResult = await db.collection('uni-id-users')
      .where({ _id: userId })
      .field({
        nickname: true,
        username: true,
        mobile: true,
        avatar_file: true,
        register_date: true,
        last_login_date: true,
        status: true
      })
      .get();

    if (!userResult.data || userResult.data.length === 0) {
      return { code: 404, msg: '用户不存在' };
    }

    const user = userResult.data[0];

    // 组装返回数据
    const profileData = {
      id: user._id,
      nickname: user.nickname || '未设置',
      username: user.username || '',
      mobile: user.mobile || '',
      avatar: user.avatar_file?.url || '',
      register_date: user.register_date || user.register_date,
      last_login_date: user.last_login_date || user.last_login_date,
      status: user.status || 0,
      isOnline: false // 可以根据实际情况判断
    };

    return {
      code: 200,
      msg: '获取成功',
      data: profileData
    };
  } catch (error) {
    console.error('获取用户资料失败:', error);
    return {
      code: 500,
      msg: '获取用户资料失败: ' + error.message,
      data: null
    };
  }
}

// 获取用户统计数据
async function getUserStatistics({ userId }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 查询发布的任务数
    const publishedTasksResult = await db.collection('taskList')
      .where({ 
        publisher_id: userId,
        is_deleted: db.command.neq(true)
      })
      .count();

    // 查询完成的任务数（作为接单者）
    const completedTasksResult = await db.collection('taskList')
      .where({ 
        receiver_id: userId,
        status: 'completed',
        is_deleted: db.command.neq(true)
      })
      .count();

    // 查询用户信息
    const userResult = await db.collection('users').doc(userId).get();
    let points = 0;
    let creditScore = 0;
    
    if (userResult.data && userResult.data.length > 0) {
      const user = userResult.data[0];
      points = user.points || 0;
      creditScore = user.creditScore || 0;
    }
    
    // 如果users表没有积分信息，尝试从user_points表查询
    if (points === 0) {
      try {
        const pointsResult = await db.collection('user_points')
          .where({ user_id: userId })
          .field({ points: true })
          .get();
        
        if (pointsResult.data && pointsResult.data.length > 0) {
          points = pointsResult.data[0].points || 0;
        }
      } catch (pointsError) {
        console.log('积分表不存在或查询失败，使用默认值0');
      }
    }

    const statisticsData = {
      publishedTasks: publishedTasksResult.total || 0,
      completedTasks: completedTasksResult.total || 0,
      points: points,
      creditScore: creditScore
    };

    return {
      code: 200,
      msg: '获取成功',
      data: statisticsData
    };
  } catch (error) {
    console.error('获取用户统计失败:', error);
    return {
      code: 500,
      msg: '获取用户统计失败: ' + error.message,
      data: null
    };
  }
}

// 调整用户积分
async function adjustUserPoints({ userId, points }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  if (points === undefined || points === null) {
    return { code: 400, msg: '缺少积分参数' };
  }

  try {
    // 检查用户积分记录是否存在
    const pointsResult = await db.collection('user_points')
      .where({ user_id: userId })
      .get();

    let newPoints = 0;

    if (pointsResult.data && pointsResult.data.length > 0) {
      // 记录存在，更新积分
      const currentPoints = pointsResult.data[0].points || 0;
      newPoints = currentPoints + points;
      
      // 确保积分不为负数
      if (newPoints < 0) newPoints = 0;

      await db.collection('user_points')
        .doc(pointsResult.data[0]._id)
        .update({
          points: newPoints,
          update_time: new Date()
        });
    } else {
      // 记录不存在，创建新记录
      newPoints = points > 0 ? points : 0;
      
      await db.collection('user_points')
        .add({
          user_id: userId,
          points: newPoints,
          create_time: new Date(),
          update_time: new Date()
        });
    }

    // 添加积分变动历史记录
    try {
      await db.collection('user_points_history')
        .add({
          user_id: userId,
          change_amount: points,
          change_type: points > 0 ? 'admin_add' : 'admin_deduct',
          description: `管理员调整积分：${points > 0 ? '+' : ''}${points}`,
          create_time: new Date()
        });
    } catch (historyError) {
      console.log('积分历史记录添加失败:', historyError);
    }

    return {
      code: 200,
      msg: '积分调整成功',
      data: { newPoints: newPoints }
    };
  } catch (error) {
    console.error('调整积分失败:', error);
    return {
      code: 500,
      msg: '调整积分失败: ' + error.message,
      data: null
    };
  }
}

// 切换用户状态（启用/禁用）
async function toggleUserStatus({ userId, status }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  if (status === undefined || status === null) {
    return { code: 400, msg: '缺少状态参数' };
  }

  try {
    // 更新用户状态
    await db.collection('uni-id-users')
      .doc(userId)
      .update({
        status: status
      });

    // 如果是禁用操作，可以添加警告记录
    if (status !== 0) {
      try {
        await db.collection('user_warnings')
          .add({
            user_id: userId,
            warning_type: 'account_disabled',
            warning_reason: '管理员禁用账号',
            created_by: 'admin',
            create_time: new Date()
          });
      } catch (warningError) {
        console.log('添加警告记录失败:', warningError);
      }
    }

    return {
      code: 200,
      msg: status === 0 ? '启用成功' : '禁用成功',
      data: { status: status }
    };
  } catch (error) {
    console.error('切换用户状态失败:', error);
    return {
      code: 500,
      msg: '切换用户状态失败: ' + error.message,
      data: null
    };
  }
}

// 搜索消息（支持关键词搜索、日期范围筛选、消息类型筛选）
async function searchMessages({ userId, keyword = '', startDate = null, endDate = null, messageType = null, page = 1, pageSize = 50 }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 构建基础查询条件（该用户与客服的对话）
    let whereConditions = [
      db.command.or([
        db.command.and([
          { senderId: userId },
          { receiverId: 'customer_service' }
        ]),
        db.command.and([
          { senderId: 'customer_service' },
          { receiverId: userId }
        ])
      ])
    ];

    // 关键词搜索（仅搜索文本消息）
    if (keyword && keyword.trim()) {
      whereConditions.push({
        content: new RegExp(keyword, 'i')
      });
    }

    // 日期范围筛选
    if (startDate) {
      whereConditions.push({
        createTime: db.command.gte(new Date(startDate))
      });
    }
    if (endDate) {
      whereConditions.push({
        createTime: db.command.lte(new Date(endDate))
      });
    }

    // 消息类型筛选
    if (messageType) {
      whereConditions.push({
        messageType: messageType
      });
    }

    // 组合所有条件
    const whereCondition = db.command.and(whereConditions);

    // 查询消息
    const result = await db.collection('customer-service-messages')
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    // 统计总数
    const countResult = await db.collection('customer-service-messages')
      .where(whereCondition)
      .count();

    // 处理消息数据（与getMessages类似的处理）
    const processedMessages = await Promise.all(result.data.reverse().map(async (msg) => {
      let content = msg.content;
      let imageUrl = msg.imageUrl;
      
      if (msg.messageType === 'image') {
        const urlToProcess = imageUrl || content;
        
        if (urlToProcess && urlToProcess.startsWith('cloud://')) {
          try {
            const getTempUrlRes = await uniCloud.getTempFileURL({
              fileList: [urlToProcess]
            });
            
            if (getTempUrlRes.fileList && getTempUrlRes.fileList.length > 0) {
              content = getTempUrlRes.fileList[0].tempFileURL || urlToProcess;
            }
          } catch (error) {
            console.log('获取图片临时链接失败:', error);
            content = urlToProcess;
          }
        } else if (urlToProcess && (urlToProcess.startsWith('http://') || urlToProcess.startsWith('https://'))) {
          content = urlToProcess;
        }
        
        if (!content || (!content.startsWith('http://') && !content.startsWith('https://'))) {
          content = '[图片]';
        }
      }
      
      let senderName, senderAvatar;
      if (msg.senderId === 'customer_service') {
        senderName = '客服小助手';
        senderAvatar = '';
      } else {
        senderName = msg.senderNickname || '用户';
        senderAvatar = msg.senderAvatar || '';
      }
      
      return {
        id: msg._id,
        type: msg.messageType,
        content: content,
        imageUrl: msg.imageUrl,
        senderName: senderName,
        isAdmin: msg.senderId === 'customer_service',
        createTime: msg.createTime,
        status: msg.status,
        avatar: senderAvatar
      };
    }));

    return {
      code: 200,
      msg: '搜索成功',
      data: {
        messages: processedMessages,
        total: countResult.total,
        page: page,
        pageSize: pageSize,
        hasMore: (page * pageSize) < countResult.total
      }
    };
  } catch (error) {
    console.error('搜索消息失败:', error);
    return {
      code: 500,
      msg: '搜索消息失败: ' + error.message,
      data: null
    };
  }
}

// 获取会话统计信息
async function getMessageStatistics({ userId }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 查询所有与该用户的聊天消息
    const messagesResult = await db.collection('customer-service-messages')
      .where(db.command.or([
        db.command.and([
          { senderId: userId },
          { receiverId: 'customer_service' }
        ]),
        db.command.and([
          { senderId: 'customer_service' },
          { receiverId: userId }
        ])
      ]))
      .get();

    const messages = messagesResult.data;
    
    if (messages.length === 0) {
      return {
        code: 200,
        msg: '获取成功',
        data: {
          totalMessages: 0,
          textMessages: 0,
          imageMessages: 0,
          userMessages: 0,
          adminMessages: 0,
          firstMessageTime: null,
          lastMessageTime: null,
          conversationDays: 0
        }
      };
    }

    // 统计各类消息数量
    const totalMessages = messages.length;
    const textMessages = messages.filter(m => m.messageType === 'text').length;
    const imageMessages = messages.filter(m => m.messageType === 'image').length;
    const userMessages = messages.filter(m => m.senderId === userId).length;
    const adminMessages = messages.filter(m => m.senderId === 'customer_service').length;

    // 获取首次和最后消息时间
    const times = messages.map(m => new Date(m.createTime).getTime()).sort((a, b) => a - b);
    const firstMessageTime = new Date(times[0]);
    const lastMessageTime = new Date(times[times.length - 1]);
    
    // 计算会话跨度（天数）
    const conversationDays = Math.ceil((lastMessageTime - firstMessageTime) / (1000 * 60 * 60 * 24));

    return {
      code: 200,
      msg: '获取成功',
      data: {
        totalMessages,
        textMessages,
        imageMessages,
        userMessages,
        adminMessages,
        firstMessageTime,
        lastMessageTime,
        conversationDays: conversationDays > 0 ? conversationDays : 1
      }
    };
  } catch (error) {
    console.error('获取统计信息失败:', error);
    return {
      code: 500,
      msg: '获取统计信息失败: ' + error.message,
      data: null
    };
  }
}

// 导出消息记录
async function exportMessages({ userId, format = 'json', startDate = null, endDate = null }) {
  if (!userId) {
    return { code: 400, msg: '缺少用户ID' };
  }

  try {
    // 构建查询条件
    let whereConditions = [
      db.command.or([
        db.command.and([
          { senderId: userId },
          { receiverId: 'customer_service' }
        ]),
        db.command.and([
          { senderId: 'customer_service' },
          { receiverId: userId }
        ])
      ])
    ];

    // 日期范围筛选
    if (startDate) {
      whereConditions.push({
        createTime: db.command.gte(new Date(startDate))
      });
    }
    if (endDate) {
      whereConditions.push({
        createTime: db.command.lte(new Date(endDate))
      });
    }

    const whereCondition = db.command.and(whereConditions);

    // 查询所有消息
    const result = await db.collection('customer-service-messages')
      .where(whereCondition)
      .orderBy('createTime', 'asc')
      .get();

    if (result.data.length === 0) {
      return {
        code: 200,
        msg: '没有可导出的消息',
        data: {
          content: '',
          filename: ''
        }
      };
    }

    // 获取用户信息
    let userNickname = '用户';
    try {
      const userResult = await db.collection('uni-id-users')
        .where({ _id: userId })
        .field({ nickname: true })
        .get();
      
      if (userResult.data && userResult.data.length > 0) {
        userNickname = userResult.data[0].nickname || '用户';
      }
    } catch (error) {
      console.log('获取用户信息失败:', error);
    }

    let exportContent = '';
    let filename = '';

    if (format === 'json') {
      // JSON格式导出
      const exportData = result.data.map(msg => ({
        时间: new Date(msg.createTime).toLocaleString('zh-CN'),
        发送者: msg.senderId === 'customer_service' ? '客服小助手' : (msg.senderNickname || userNickname),
        消息类型: msg.messageType === 'text' ? '文本' : msg.messageType === 'image' ? '图片' : '其他',
        内容: msg.content,
        状态: msg.status === 'read' ? '已读' : msg.status === 'sent' ? '已发送' : '未读'
      }));
      
      exportContent = JSON.stringify(exportData, null, 2);
      filename = `聊天记录_${userNickname}_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.json`;
    } else {
      // 文本格式导出
      exportContent = `聊天记录 - ${userNickname}\n`;
      exportContent += `导出时间：${new Date().toLocaleString('zh-CN')}\n`;
      exportContent += `消息总数：${result.data.length}\n`;
      exportContent += `\n${'='.repeat(50)}\n\n`;
      
      result.data.forEach(msg => {
        const time = new Date(msg.createTime).toLocaleString('zh-CN');
        const sender = msg.senderId === 'customer_service' ? '客服小助手' : (msg.senderNickname || userNickname);
        const content = msg.messageType === 'image' ? '[图片]' : msg.content;
        
        exportContent += `[${time}] ${sender}：\n${content}\n\n`;
      });
      
      filename = `聊天记录_${userNickname}_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.txt`;
    }

    return {
      code: 200,
      msg: '导出成功',
      data: {
        content: exportContent,
        filename: filename,
        total: result.data.length
      }
    };
  } catch (error) {
    console.error('导出消息失败:', error);
    return {
      code: 500,
      msg: '导出消息失败: ' + error.message,
      data: null
    };
  }
}

// ============= 快捷操作函数 =============

// 调整用户积分
async function adjustPoints({ userId, points }) {
  try {
    if (!userId || points === undefined || points === 0) {
      return {
        code: 400,
        msg: '参数错误',
        data: null
      };
    }
    
    // 查询用户
    const userResult = await db.collection('users').doc(userId).get();
    if (!userResult.data || userResult.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: null
      };
    }
    
    const user = userResult.data[0];
    const currentPoints = user.points || 0;
    const newPoints = Math.max(0, currentPoints + points); // 不能低于0
    
    // 更新用户积分
    await db.collection('users').doc(userId).update({
      points: newPoints,
      updateTime: new Date()
    });
    
    // 记录积分变动日志
    await db.collection('points-logs').add({
      userId: userId,
      type: points > 0 ? 'admin_add' : 'admin_deduct',
      points: Math.abs(points),
      before: currentPoints,
      after: newPoints,
      operator: 'customer_service',
      remark: `客服${points > 0 ? '增加' : '扣除'}积分`,
      createTime: new Date()
    });
    
    return {
      code: 200,
      msg: '积分调整成功',
      data: {
        oldPoints: currentPoints,
        newPoints: newPoints,
        change: points
      }
    };
  } catch (error) {
    console.error('调整积分失败:', error);
    return {
      code: 500,
      msg: '调整积分失败: ' + error.message,
      data: null
    };
  }
}

// 调整用户信用分
async function adjustCreditScore({ userId, creditScore }) {
  try {
    if (!userId || creditScore === undefined || creditScore === 0) {
      return {
        code: 400,
        msg: '参数错误',
        data: null
      };
    }
    
    // 查询用户
    const userResult = await db.collection('users').doc(userId).get();
    if (!userResult.data || userResult.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: null
      };
    }
    
    const user = userResult.data[0];
    const currentCreditScore = user.creditScore || 0;
    const newCreditScore = Math.max(0, currentCreditScore + creditScore); // 不能低于0
    
    // 更新用户信用分
    await db.collection('users').doc(userId).update({
      creditScore: newCreditScore,
      updateTime: new Date()
    });
    
    // 记录信用分变动日志
    await db.collection('credit-score-logs').add({
      userId: userId,
      type: creditScore > 0 ? 'admin_add' : 'admin_deduct',
      creditScore: Math.abs(creditScore),
      before: currentCreditScore,
      after: newCreditScore,
      operator: 'customer_service',
      remark: `客服${creditScore > 0 ? '增加' : '扣除'}信用分`,
      createTime: new Date()
    });
    
    return {
      code: 200,
      msg: '信用分调整成功',
      data: {
        oldCreditScore: currentCreditScore,
        newCreditScore: newCreditScore,
        change: creditScore
      }
    };
  } catch (error) {
    console.error('调整信用分失败:', error);
    return {
      code: 500,
      msg: '调整信用分失败: ' + error.message,
      data: null
    };
  }
}

// 更新用户信用等级（保留用于兼容性）
async function updateCreditLevel({ userId, creditLevel }) {
  try {
    if (!userId || !creditLevel) {
      return {
        code: 400,
        msg: '参数错误',
        data: null
      };
    }
    
    // 验证信用等级
    const validLevels = ['A', 'B', 'C', 'D', 'E'];
    if (!validLevels.includes(creditLevel)) {
      return {
        code: 400,
        msg: '无效的信用等级',
        data: null
      };
    }
    
    // 查询用户
    const userResult = await db.collection('users').doc(userId).get();
    if (!userResult.data || userResult.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: null
      };
    }
    
    const oldLevel = userResult.data[0].creditLevel || 'A';
    
    // 更新信用等级
    await db.collection('users').doc(userId).update({
      creditLevel: creditLevel,
      updateTime: new Date()
    });
    
    // 记录等级变更日志
    await db.collection('credit-logs').add({
      userId: userId,
      oldLevel: oldLevel,
      newLevel: creditLevel,
      operator: 'customer_service',
      remark: `客服调整信用等级：${oldLevel} → ${creditLevel}`,
      createTime: new Date()
    });
    
    return {
      code: 200,
      msg: '信用等级更新成功',
      data: {
        oldLevel: oldLevel,
        newLevel: creditLevel
      }
    };
  } catch (error) {
    console.error('更新信用等级失败:', error);
    return {
      code: 500,
      msg: '更新信用等级失败: ' + error.message,
      data: null
    };
  }
}

// 处理违规行为
async function handleViolation({ userId, violationType, violationReason, actionType }) {
  try {
    if (!userId || !violationType || !violationReason || !actionType) {
      return {
        code: 400,
        msg: '参数错误',
        data: null
      };
    }
    
    // 查询用户
    const userResult = await db.collection('users').doc(userId).get();
    if (!userResult.data || userResult.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: null
      };
    }
    
    const user = userResult.data[0];
    
    // 记录违规日志
    const violationLog = {
      userId: userId,
      userNickname: user.nickname || user.username,
      violationType: violationType,
      violationReason: violationReason,
      actionType: actionType,
      operator: 'customer_service',
      createTime: new Date()
    };
    
    await db.collection('violation-logs').add(violationLog);
    
    // 根据操作类型处理
    if (actionType === 'ban') {
      // 禁用账号
      await db.collection('users').doc(userId).update({
        status: 'banned',
        bannedReason: violationReason,
        bannedTime: new Date(),
        updateTime: new Date()
      });
      
      // 信用分清零
      const currentCreditScore = user.creditScore || 0;
      await db.collection('users').doc(userId).update({
        creditScore: 0
      });
      
      // 记录信用分变动日志
      await db.collection('credit-score-logs').add({
        userId: userId,
        type: 'ban_clear',
        creditScore: currentCreditScore,
        before: currentCreditScore,
        after: 0,
        operator: 'customer_service',
        remark: `账号禁用，信用分清零`,
        createTime: new Date()
      });
      
      return {
        code: 200,
        msg: '账号已禁用',
        data: {
          action: 'banned',
          reason: violationReason
        }
      };
    } else if (actionType === 'warning') {
      // 警告用户 - 增加警告次数
      const warningCount = (user.warningCount || 0) + 1;
      
      await db.collection('users').doc(userId).update({
        warningCount: warningCount,
        lastWarningTime: new Date(),
        lastWarningReason: violationReason,
        updateTime: new Date()
      });
      
      // 根据警告次数扣除信用分
      let creditScoreDeduct = 0;
      if (warningCount >= 5) {
        creditScoreDeduct = 50; // 5次及以上警告，扣除50分
      } else if (warningCount >= 3) {
        creditScoreDeduct = 30; // 3-4次警告，扣除30分
      } else if (warningCount >= 1) {
        creditScoreDeduct = 10; // 1-2次警告，扣除10分
      }
      
      // 扣除信用分
      const currentCreditScore = user.creditScore || 0;
      const newCreditScore = Math.max(0, currentCreditScore - creditScoreDeduct);
      
      await db.collection('users').doc(userId).update({
        creditScore: newCreditScore
      });
      
      // 记录信用分变动日志
      await db.collection('credit-score-logs').add({
        userId: userId,
        type: 'violation_deduct',
        creditScore: creditScoreDeduct,
        before: currentCreditScore,
        after: newCreditScore,
        operator: 'customer_service',
        remark: `违规警告扣除信用分（第${warningCount}次警告）`,
        createTime: new Date()
      });
      
      return {
        code: 200,
        msg: '已警告用户',
        data: {
          action: 'warning',
          warningCount: warningCount,
          creditScoreDeduct: creditScoreDeduct,
          newCreditScore: newCreditScore,
          reason: violationReason
        }
      };
    }
    
    return {
      code: 400,
      msg: '未知操作类型',
      data: null
    };
  } catch (error) {
    console.error('处理违规失败:', error);
    return {
      code: 500,
      msg: '处理违规失败: ' + error.message,
      data: null
    };
  }
}
